package cn.jxwazx.sheinspringboot.config;



import cn.jxwazx.sheinspringboot.entity.R;
import cn.jxwazx.sheinspringboot.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 全局异常处理
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler  {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINESE);
    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandler(Exception e) {

        logger.info("时间 = {}",simpleDateFormat.format(new Date()));

        logger.error(simpleDateFormat.format(new Date()),e);

        e.printStackTrace();

        StackTraceElement[] stackTrace = e.getStackTrace();

        String s = JSONUtil.toJsonStr(stackTrace);

        //绑定异常是需要明确提示给用户的
        if (e instanceof MyException) {
            MyException exception = (MyException)e;
            return R.error(exception.getMessage());
        }
        if(e instanceof NullPointerException)
        {
            return R.error("空指针异常" + s);

        }
        //参数绑定异常
        if (e instanceof BindException || e instanceof MethodArgumentNotValidException) {
            if (e instanceof BindException) {
                BindingResult bindingResult = ((BindException) e).getBindingResult();
                return R.error((bindingResult.getAllErrors().get(0).getDefaultMessage()));

            }else {
                BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
                return R.error((bindingResult.getAllErrors().get(0).getDefaultMessage()));

            }

        }


        return R.error(e.getMessage()+s);

    }
}